package com.sqgxy.service.impl;

import com.sqgxy.dao.FileDao;
import com.sqgxy.dao.impl.FileDaoImpl;
import com.sqgxy.pojo.po.FileDate;
import com.sqgxy.service.FileService;
import net.sf.json.JSONObject;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    private final FileDao dao;

    public FileServiceImpl(FileDao dao) {
        this.dao = dao;
    }

    @Override
    public String upload(MultipartFile file, HttpServletRequest request) {
        InputStream is = null;
        try {
            is = file.getInputStream();
            if (is.available() == 0) return "图片格式不正确";
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 设置文件存放路径,根据日期放置
        UUID uuid = UUID.randomUUID();

        String originalFilename = file.getOriginalFilename();
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filename = uuid + "." + suffixName;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String date = sdf.format(new Date());
        String realPath = BASE_DIR + date + "/" + filename;


        try {
            // 将文件放入磁盘中去
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realPath));
        } catch (IOException e) {
            e.printStackTrace();
        }

        // TODO图片的元数据放入到数据库中去
        // 文件大小、文件类型，原始文件名，创建时间，文件保存目录地址等元数据记录至数据库中 uuid
        // 创建时间在数据库插入时自动添加
        // size   suffixName originalFilename    realPath, uuid
        long size = file.getSize();
        FileDate fileDate = new FileDate();
        fileDate.setName(originalFilename);
        fileDate.setPath(realPath);
        fileDate.setType(suffixName.substring(1));
        fileDate.setSize(size);
        fileDate.setUuid(uuid.toString());
        dao.save(fileDate);

        // 返回UUID
        return uuid.toString();
    }

    @Override
    public String download(String id) {
        return dao.get(id).getPath();
    }

    @Override
    public String getDate(String id) {
        FileDate fileDate = dao.get(id);
        JSONObject obj = new JSONObject();
        obj.put("id", fileDate.getId());
        obj.put("name", fileDate.getName());
        obj.put("size", fileDate.getSize());
        obj.put("type", fileDate.getType());
        obj.put("date", fileDate.getDate());
        obj.put("path", fileDate.getPath());
        obj.put("uuid", fileDate.getUuid());
        return obj.toString(2);
    }
}
